<script setup lang="ts" generic="T extends Record<string, unknown>, K = never">
import { ref, watch } from 'vue';
import { VueDraggable } from 'vue-draggable-plus';
import type { STableProps } from '@surely-vue/table';
import { $t } from '@/locales';

type MyColumn = {
  checked: true;
  resizable?: boolean;
  width?: number;
};

type TableColumn = STableProps['columns'] & MyColumn;

defineOptions({
  name: 'TableColumnSetting'
});

const columns = defineModel<TableColumn[]>('columns', {
  required: true
});

const tableColumns = ref(columns.value);

function handleChange(val: any) {
  if (val.checked) {
    val.colSpan = 1;
  } else {
    val.colSpan = 0;
  }
}

watch(
  () => tableColumns.value,
  val => {
    const arr = val.filter(item => item.checked);
    columns.value = [...arr];
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <APopover placement="bottomRight" trigger="click">
    <AButton size="small" class="mini-btn">
      <template #icon>
        <icon-ant-design-setting-outlined class="align-sub text-icon" />
      </template>
      <span class="ml-3px">{{ $t('common.columnSetting') }}</span>
    </AButton>
    <template #content>
      <!--
 <div
          v-for="item in tableColumns"
          :key="item.key"
          class="h-36px flex-y-center rd-4px hover:(bg-primary bg-opacity-20)"
        >
          <icon-mdi-drag class="mr-8px h-full cursor-move text-icon" />
          <ACheckbox v-model:checked="item.checked" class="none_draggable flex-1" @change="handleChange(item)">
            {{ item.title }}
          </ACheckbox>
        </div>
-->
      <div class="h-auto w-350px">
        <VueDraggable v-model="tableColumns" :animation="150" filter=".none_draggable" class="flex flex-wrap">
          <div
            v-for="item in tableColumns"
            :key="item.key"
            class="h-40px w-50% flex-y-center rd-4px pr-15px hover:(bg-primary bg-opacity-20)"
          >
            <icon-mdi-drag class="mr-8px h-full cursor-move text-icon" />
            <ACheckbox v-model:checked="item.checked" class="none_draggable flex-1" @change="handleChange(item)">
              {{ item.title }}
            </ACheckbox>
          </div>
        </VueDraggable>
      </div>
    </template>
  </APopover>
</template>

<style scoped></style>
